<?php
/**
 * Created by PhpStorm.
 * User: 陶然
 * Date: 2019/4/11
 * Time: 18:55
 * SOURCE: 中国大陆工时规管现况（标准工时）：
 *              一天工作时间为8小时，平均每周工时不超过40小时;
 *              加班上限为一天3小时及一个月36小时，逾时工作薪金不低于平日工资的150％。
 *              而一周最高工时则为48小时。平均每月计薪天数为21.75天。
 * TO: 我是陶然,健康撸代码,拒绝通宵。
 * CLASS: < 活动 >
 */
namespace App\HttpController\Taoran;

use alipay\AppPay;
use App\Common\Checking;
use App\HttpController\Taoran\Functions\Databases;
use App\HttpController\Taoran\Functions\Publics;
use App\HttpController\V1\Auth;
use wechatpay\WxApp;
class Activitys extends Auth
{
    /**
     * @return bool
     * 聚聚报名页面渲染
     */
    function sign_up()
    {
        $ids=$this->input('ids','post');
        if (intval($ids)!=$ids){
            return $this->writeJson(201,'','???');
        }
        $classId=$this->db->where('pid',3)->getColumn('study_class','id');
        $study=$this->db->where('id',$ids)->where('class_id',$classId,'in')->getOne('study');
        if (!$study){
            return $this->writeJson(202,'','该活动已下线');
        }
        if ($this->db->where('user_id',$this->user->id)->where('activity_id',$ids)->where('status',1)->getOne('activitys')){
            return $this->writeJson(203,'','该活动已报名');
        }
        $userData=$this->db->where('id',$this->user->id)->getOne('users','mobile,level');
        $data=[
            'market_price'=>in_array($userData['level'],[1,4])?$study['market_price']:$study['vip_price'],
            'mobile'=>$userData['mobile'],
            'id'=>$ids
        ];
        return $this->writeJson(200,$data);
    }

    /**
     * @return bool
     * 报名
     */
    function sub_up()
    {
        $ids = $this->input('ids');
        if (intval($ids) != $ids) {
            return $this->writeJson(201, '', '???');
        }
        $num = $this->input('num');
        if (intval($num) != $num || $num < 1) {
            return $this->writeJson(202, '', '???');
        }
        $userData = $this->db->where('id', $this->user->id)->getOne('users');
        $pass = $this->input('pass');

        $payment = $this->input('payment');
        if (!in_array($payment, [1, 2, 3])) {
            return $this->writeJson(202, '', '???');
        }
        $classId = $this->db->where('pid', 3)->getColumn('study_class', 'id');
        $study = $this->db->where('id', $ids)->where('class_id', $classId, 'in')->getOne('study');
        if (!$study) {
            return $this->writeJson(203, '', '该活动已下线');
        }
        if ($this->db->where('user_id', $this->user->id)->where('activity_id', $ids)->where('status',1)->getOne('activitys')) {
            return $this->writeJson(204, '', '该活动已报名');
        }
        $out_trade_no=Checking::ordeSnByUnique('order_num',$this->db,'activitys');
        $data = Databases::activitys($userData, $num, $study, $payment, $ids,$out_trade_no);
//        $data['money']=0.01;
        switch ($payment) {
            case 1:    //TODO 微信
                $data['status']=0;
                $sql = $this->db->insert('activitys', $data);
                if (!$sql) {
                    return $this->writeJson(-3, null, '创建订单失败');
                }
                $notify_url=API_URL.'/v1/notify/wx_activity';
                $WxApp=new WxApp();
                $json=$WxApp->getPrePayOrder('明心堂-报名活动',$data['order_num'],$data['money'],$notify_url,$this->request()->getHeaders()['real-ip'][0]);
                return $this->writeJson(200, $json, '成功');
                break;
            case 2:    //TODO 支付宝
                $data['status']=0;
                $sql = $this->db->insert('activitys', $data);
                if (!$sql) {
                    return $this->writeJson(-3, null, '创建订单失败');
                }
                $notify_url=API_URL.'/v1/notify/ali_activity';//异步地址
                $AliPay=new AppPay();
                $json=$AliPay->app_pay('明心堂-报名活动',$data['order_num'],$data['money'],$notify_url);
                return $this->writeJson(200, $json, '成功');
                break;
            case 3:    //奖学金
                if (intval($pass) != $pass || !Checking::checkPassword($userData['pay_password'],$pass)) {
                    return $this->writeJson(202, '', '密码不正确');
                }
                if ($userData['balance'] < $data['money']) {
                    return $this->writeJson(205, '', '奖学金数量不足');
                }
                $publics = new Publics();
                try {
                    $this->db->startTransaction();
                    $reward = $publics->call_inspiration($this->user->id, $data['money'], 3, $this->db);
                    if (!$reward) {
                        throw new \Exception('活动报名失败', 205);
                    }
                    $data['status']=1;
                    $data['updatetime']=date('YmdHis');
                    $sql = $this->db->insert('activitys', $data);
                    $this->db->insert('users_account_log',[
                        'user_id'=>$this->user->id,
                        'type'=>10,
                        'class'=>2,
                        'coin_type'=>'study',
                        'money'=>$data['money'],
                        'remark'=>'活动报名',
                        'createtime'=>date('YmdHis'),
                        'before_money'=>$userData['balance']
                    ]);
                    if (!$sql) {
                        throw new \Exception('稍后重试', 206);
                    }
                    $sql = $this->db->where('id', $this->user->id)->setDec('users', 'balance', $data['money']);
                    if (!$sql) {
                        throw new \Exception('奖学金扣除失败', 207);
                    }
                    $this->db->commit();
                } catch (\Exception $e) {
                    $this->db->rollback();
                    return $this->writeJson($e->getCode(), '', $e->getMessage());
                }
                break;
        }
        return $this->writeJson(200, '', '报名成功');
    }
}